import { fetchONES } from '@ones-op/node-fetch'
import { Logger } from '@ones-op/node-logger'
// import { OPFetch } from '@ones-op/fetch'
import type { PluginRequest, PluginResponse } from '@ones-op/node-types'
import { downloadFile } from '@ones-op/node-ability'
import { importSQL } from '@ones-op/node-database'

// Method called when the team level plugin is being installed.
export async function Install() {
  Logger.info(`[Plugin] Install 生命周期Install`)
  Logger.info(`数据库表初始化`)
  return importSQL('plugin.sql')
}

// Method called when the team level plugin is being launched.
export async function Enable() {
  Logger.info('[Plugin] Enable')
}

// Method called when the team level plugin is being suspended.
export function Disable() {
  Logger.info('[Plugin] Disable')
}

// Method called when the team level plugin is being uninstalled.
export function UnInstall() {
  Logger.info('[Plugin] UnInstall')
}

// Method called when the team level plugin is being upgraded.
export function Upgrade(oldPluginInfo) {
  const oldVersion = oldPluginInfo.version
  Logger.info('[Plugin] Upgrade', 'old version:', oldVersion)
}

/*
    Method called when the organization level plugin is being installed.

    Request parameter description:
    request:
      request.parsedHeaders state multi-language, for example,when the request user context is chinese,
      the parameter will be {"Accept-Language":["zh"]}, there are other cases like {"Accept-Language":["en"]},
      {"Accept-Language":["ja"]}.
    teamUUIDList:
      The uuid list with the team which installed by this time.
    firstInstall:
      True if plugin has never been installed.
 */
export async function OrgInstall(
  request: PluginRequest,
  teamUUIDList: string[],
  firstInstall: boolean
) {
  Logger.info('[Plugin] OrgInstall')
}

/*
    Method called when the organization level plugin is being launched.

    Request parameters description:
    request:
      request.parsedHeaders state multi-language, for example,when the request user context is chinese,
      the parameter will be {"Accept-Language":["zh"]}, there are other cases like {"Accept-Language":["en"]},
      {"Accept-Language":["ja"]}.
    teamUUIDList:
      The uuid list with the team which launched by this time.

    Response parameters description:
      Return the failed team uuid list.
 */
export function OrgEnable(
  request: PluginRequest,
  teamUUIDList: string[]
): void | string[] | Promise<string[]> {
  Logger.info('[Plugin] OrgEnable')
  return []
}

/*
    Method called when the organization level plugin is being suspended.

    Request parameters description:
    request:
      request.parsedHeaders state multi-language, for example,when the request user context is chinese,
      the parameter will be {"Accept-Language":["zh"]}, there are other cases like {"Accept-Language":["en"]},
      {"Accept-Language":["ja"]}.
    teamUUIDList:
      The uuid list with the team which suspended by this time.

    Response parameters description:
      Return the failed team uuid list.
 */
export function OrgDisable(
  request: PluginRequest,
  teamUUIDList: string[]
): void | string[] | Promise<string[]> {
  Logger.info('[Plugin] OrgDisable')
  return []
}

/*
    Method called when the organization level plugin is being uninstalled.

    Request parameters description:
    request:
      request.parsedHeaders state multi-language, for example,when the request user context is chinese,
      the parameter will be {"Accept-Language":["zh"]}, there are other cases like {"Accept-Language":["en"]},
      {"Accept-Language":["ja"]}.
    teamUUIDList:
      The uuid list with the team which uninstalled by this time.
 */
export function OrgUnInstall(request: PluginRequest, teamUUIDList: string[]) {
  Logger.info('[Plugin] OrgUnInstall')
}

/*
    Method called when the organization level plugin is being upgraded.

    Request parameters description:
    request:
      request.parsedHeaders state multi-language, for example,when the request user context is chinese,
      the parameter will be {"Accept-Language":["zh"]}, there are other cases like {"Accept-Language":["en"]},
      {"Accept-Language":["ja"]}.
    teamUUIDList:
      The uuid list with the team which upgraded by this time.
 */
export function OrgUpgrade(oldPluginInfo: any, request: PluginRequest, teamUUIDList: string[]) {
  const oldVersion = oldPluginInfo.version
  Logger.info('[Plugin] OrgUpgrade', 'old version:', oldVersion)
}

// example function
export async function hello(request: PluginRequest): Promise<PluginResponse> {
  const body = request.body || {}
  Logger.info('[Plugin] hello ======= 请求成功')
  return {
    body: {
      res: 'hello world',
      requestBody: body,
    },
  }
}

// 根据ID调用接口获取项目信息
export async function getProjectInfoDetail(teamId: string, projectId: string) {
  const url = `/team/${teamId}/projects/info?ids=${projectId}`
  const response = await fetchONES({
    path: url,
    method: 'GET',
  })
  const projects = (response?.body as any).projects
  if (projects.length === 0) {
    return {}
  } else {
    return projects[0]
  }
}

export async function getProjectTask(teamId: string, projectId: string, status: string) {
  const url = `/team/${teamId}/items/graphql`
  const response = await fetchONES({
    path: url,
    method: 'POST',
    body: {
      query: `
          query {
            tasks(
              filter: {
                project: { uuid_equal: "${projectId}" },
                status: {
                },
              }
            ) {
              uuid
              name
              deadline
              statusCategory
              status {
                  name
              }
            }
          }
        `,
    },
  })
  let tasks = (response?.body as any)?.data?.tasks || []
  // 查询状态为未开始的任务
  if (tasks.length > 0) {
    if (status) {
      tasks = tasks.filter((item) => item.status.name === status)
    }
  }

  return tasks
}

export async function getProjectInfoApi(teamId: string, projectName: string) {
  let projects = await getProjectInfoAll(teamId)
  if (projectName) {
    projects = projects.filter((item) => item.name === projectName)
  }
  return projects
}

// 获取团队下全部的项目
export async function getProjectInfoAll(teamId: string) {
  const url = `/team/${teamId}/projects/all`
  const response = await fetchONES({
    path: url,
    method: 'GET',
  })
  const projects = (response?.body as any).projects
  if (projects.length === 0) {
    return {}
  } else {
    return projects
  }
}

// 考题一，获取项目信息  1-1
export async function getProjectInfo(request: PluginRequest): Promise<PluginResponse> {
  const body = request.body as any
  const headers = request.headers
  const teamId = headers['Ones-Check-Id']
  const projects = await getProjectInfoApi(teamId, body.projectName)
  return {
    body: projects,
  }
}

// 考题 1-2
export async function getTaskInfo(request: PluginRequest): Promise<PluginResponse> {
  const body = request.body as any
  const headers = request.headers
  const teamId = headers['Ones-Check-Id']
  let projects = await getProjectInfoAll(teamId)
  if (body.projectName) {
    projects = projects.filter((item) => item.name === body.projectName)
  }
  if (projects.length > 0) {
    const projectId = projects[0].uuid
    const tasks = await getProjectTask(teamId, projectId, body.taskStatus)
    return {
      body: {
        project: projects.length > 0 ? projects[0] : {},
        tasks,
      },
    }
  }
  return {
    body: projects,
  }
}

// 考题 1-3
export async function getTaskManHours(request: PluginRequest): Promise<PluginResponse> {
  const body = request.body as any
  const headers = request.headers
  const teamId = headers['Ones-Check-Id']
  const projects = await getProjectInfoApi(teamId, body.projectName)

  if (projects.length > 0) {
    const projectId = projects[0].uuid
    const tasks = await getProjectTask(teamId, projects[0].uuid, body.taskStatus)
    const taskIds = tasks.map((item) => item.uuid)
    // 把 taskIds 变成 ["taskId1", "taskId2"] 的形式
    const taskStr = taskIds.join(`""`)

    const url = `/team/${teamId}/items/graphql`
    // 简单模式和复杂模式就是增加 mode 参数,分别是 工时模式 [detailed:汇总模式, simple:简单模式]
    const response = await fetchONES({
      path: url,
      method: 'POST',
      body: {
        query: `
          query {
            manhours(
              filter: {
                project: { uuid_equal: "${projectId}" },
                task: {
                  uuid_in: [${taskStr}]
                }
              }
            ) {
              mode
              key
              hours
              startTime
              description
              type
              owner {
                uuid
                name
              }
              task {
                uuid
                name
              }
            }
          }
        `,
      },
    })
    const manhours = (response?.body as any)?.data?.manhours || []

    return {
      body: {
        project: projects.length > 0 ? projects[0] : {},
        tasks,
        manhours,
      },
    }
  }
  return {
    body: projects,
  }
}

// 考题 1-4 实现下载功能
export async function downloadFiles(request: PluginRequest): Promise<PluginResponse> {
  const headers = request.headers
  const teamId = headers['Ones-Check-Id']
  const filename = headers['Filename']
  const url = await downloadFile(filename, 60 * 60, teamId)
  return {
    body: {
      url,
    },
  }
}

// export * from './timer-task'
export * from './task'
export * from './database'
